<?php

/**
 * This is the model class for table "tbusuarios".
 *
 * The followings are the available columns in table 'tbusuarios':
 * @property string $Us_idusuario_PK
 * @property string $Us_nombrecompleto
 * @property string $username
 * @property string $password
 * @property string $Us_telefono
 * @property string $Us_direccion
 * @property string $Us_cedula
 *
 * The followings are the available model relations:
 * @property Tbajusteinventario[] $tbajusteinventarios
 * @property Tbbitacora[] $tbbitacoras
 * @property Tbderechos[] $tbderechoses
 * @property Tbhistorialcontraseña[] $tbhistorialcontraseñas
 */
class usuarios extends CActiveRecord
{
	//Voy a agregar esto para validar el password.....

	const WEAK=0;
	const STRONG=1;
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbusuarios';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('Us_idusuario_PK, Us_nombrecompleto, username, password, Us_telefono, Us_direccion, Us_cedula', 'required'),
			array('Us_idusuario_PK', 'length', 'min'=>3, 'max'=>20),
			array('username','length','min'=>8,'max'=>20),
			array('Us_cedula','length','min'=>9,'max'=>20),
			array('Us_nombrecompleto, Us_direccion', 'length', 'max'=>50),
			array('password', 'length', 'min'=>8, 'max'=>100),
			//validación para que el valor sea numero entero.
			array('Us_telefono','length','min'=>8,'max'=>15),
			//Validacion agregada el dia 27/01/2014. hacer un campo unico.
			array('Us_idusuario_PK','unique','attributeName'=>'Us_idusuario_PK'),
			//ARREGO ARRAY PARA AGREGAR LA FUNCION QUE ME VALIDA LA CONTRASENA.
			array('password','passwordStrength','strength'=>self::STRONG),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('Us_idusuario_PK, Us_nombrecompleto, username, password, Us_telefono, Us_direccion, Us_cedula', 'safe', 'on'=>'search'),
		);
	}
	//Funcion validacion de password.
	public function passwordStrength($attribute,$params)
	{
		

		if ($params['strength']===self::WEAK)
		$params='/^(?=.*[a-zA-Z0-9]).{5,}$/';
		elseif($params['strength']===self::STRONG)
			 $pattern = '/^(?=.*\d(?=.*\d))(?=.*[a-zA-Z](?=.*[a-zA-Z])).{5,}$/';
			if(!preg_match($pattern, $this->$attribute))
      $this->addError($attribute, 'Su contraseña no es robusta intente con otra!');

	}


	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'tbajusteinventarios' => array(self::HAS_MANY, 'Tbajusteinventario', 'Us_idusuario_FK'),
			'tbbitacoras' => array(self::HAS_MANY, 'Tbbitacora', 'Us_idusuario_FK'),
			'tbderechoses' => array(self::HAS_MANY, 'Tbderechos', 'Us_idusuario_FK'),
			'tbhistorialcontraseñas' => array(self::HAS_MANY, 'Tbhistorialcontraseña', 'Us_idusuario_FK'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'Us_idusuario_PK' => 'Código usuario',
			'Us_nombrecompleto' => 'Nombre completo',
			'username' => 'Usuario',
			'password' => 'Contraseña',
			'Us_telefono' => 'Teléfono',
			'Us_direccion' => 'Dirección',
			'Us_cedula' => 'Cedúla',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('Us_idusuario_PK',$this->Us_idusuario_PK,true);
		$criteria->compare('Us_nombrecompleto',$this->Us_nombrecompleto,true);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('Us_telefono',$this->Us_telefono,true);
		$criteria->compare('Us_direccion',$this->Us_direccion,true);
		$criteria->compare('Us_cedula',$this->Us_cedula,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination' => array(  'pageSize'=>Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']))
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return usuarios the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	public function validatePassword($password){
return $this->hashPassword($password)===$this->password;
}
 
public function hashPassword($password){
return md5($password);
}
public function beforeSave() {
        $pass = md5($this->password);
        $this->password = $pass;
        return true;
    }
}
